package GUI;

import GUI.añadido.AñadirAviso;
import GUI.modelosTablas.SearchBoxModel;
import GUI.modelosTablas.ServiciosPrestadosDefaultTableModel;
import GUI.ver.VerPresupuesto;
import base.Aviso;
import base.Equipo;
import base.Estado;
import base.Peticion;
import base.Servicio;
import base.Tarea;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.Timer;
import negocio.Usuario;
import negocio.bd.BDPeticiones;
import negocio.bd.BDServicios;
import negocio.bd.BDTareas;
import negocio.bd.BDPresupuestos;
import java.util.GregorianCalendar;
import javax.swing.JOptionPane;
import negocio.bd.BDAlmacenEquipos;
import negocio.bd.BDAviso;
import utiles.ConversorFecha;

/**
 *
 * @author EFREN
 */
public class VistaTecnico extends javax.swing.JFrame {
    SearchBoxModel modeloServicios;
    ServiciosPrestadosDefaultTableModel modeloServiciosPrestados;
    private Tarea tareaActual;
    boolean isFirst;
    private Usuario user;
    /**
     * Creates new form VistaTecnico
     */
    public VistaTecnico(Usuario user) {
        initComponents();
        setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("/img/ico.png")));
        this.user = user;
       if (user.getPermisos() == Usuario.TECNICO || user.getPermisos() == Usuario.ADMINISTRADOR){
           modeloServicios = new SearchBoxModel(comboServicios, BDServicios.obtenerTodos());
           tablaServiciosPrestados.setModel(new ServiciosPrestadosDefaultTableModel(false));
           modeloServiciosPrestados = (ServiciosPrestadosDefaultTableModel)tablaServiciosPrestados.getModel();
           this.setExtendedState(JFrame.MAXIMIZED_BOTH);
       }else {
           modeloServicios = null;
           Dialogos.mostrarDialogoFaltanPermisos();
           this.setVisible(false);
       }
       lstTareasPendientes.setModel(new TareasDefaultListModel());
       Timer timer = new Timer (60000, new ActionListener () 
{ 
    @Override
    public void actionPerformed(ActionEvent e) 
    { 
        lstTareasPendientes.setModel(new TareasDefaultListModel());
     } 
     }); 

timer.setRepeats(true);
timer.start();
       
        comboServicios.setModel(modeloServicios);
        isFirst = true;
        cambiarEstadoCampos(false);
    }
public void cambiarEstadoCampos(boolean e){
    this.lblDNI.setText("");
    this.lblFecha.setText("");
    this.txtDescripcion.setText("");
    this.tablaServiciosPrestados.setModel(new ServiciosPrestadosDefaultTableModel(false));
    this.lblDNI.setEnabled(e);
    this.lblFecha.setEnabled(e);
    this.txtDescripcion.setEnabled(e);
    this.comboServicios.setEnabled(e);
    this.tablaServiciosPrestados.setEnabled(e);
    this.unidades.setEnabled(e);
    this.btnAñadir.setEnabled(e);
    this.btnQuitar.setEnabled(e);
    this.btnVerPresupuesto.setEnabled(e);
    this.btnFinalizar.setEnabled(e);
    this.btnAvisarCambios.setEnabled(e);
    this.jButton3.setEnabled(e);
}
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jDialog1 = new javax.swing.JDialog();
        jPanel4 = new javax.swing.JPanel();
        jButton2 = new javax.swing.JButton();
        jButton1 = new javax.swing.JButton();
        jSpinner1 = new javax.swing.JSpinner();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstTareasPendientes = new javax.swing.JList();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        lblDNI = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        lblFecha = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtDescripcion = new javax.swing.JTextArea();
        btnVerPresupuesto = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jScrollPane2 = new javax.swing.JScrollPane();
        tablaServiciosPrestados = new javax.swing.JTable();
        comboServicios = new javax.swing.JComboBox();
        btnAñadir = new javax.swing.JButton();
        btnQuitar = new javax.swing.JButton();
        unidades = new javax.swing.JSpinner();
        jPanel5 = new javax.swing.JPanel();
        btnAvisarCambios = new javax.swing.JButton();
        btnFinalizar = new javax.swing.JButton();

        jDialog1.setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        jDialog1.setTitle("Seleccion número");

        jButton2.setText("Cancelar");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });

        jButton1.setText("Aceptar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        jSpinner1.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addComponent(jButton1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton2))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jSpinner1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton2)
                    .addComponent(jButton1))
                .addContainerGap())
        );

        javax.swing.GroupLayout jDialog1Layout = new javax.swing.GroupLayout(jDialog1.getContentPane());
        jDialog1.getContentPane().setLayout(jDialog1Layout);
        jDialog1Layout.setHorizontalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jDialog1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );
        jDialog1Layout.setVerticalGroup(
            jDialog1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jDialog1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Gestionaitor 2000 - Menu Técnico");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Tareas pendientes", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N

        lstTareasPendientes.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lstTareasPendientes.setToolTipText("Listado de tareas pendientes de realizar.");
        lstTareasPendientes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                lstTareasPendientesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(lstTareasPendientes);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 254, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 419, Short.MAX_VALUE)
                .addContainerGap())
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Detalle de petición", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel1.setText("Descripción:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel2.setText("DNI Cliente:");

        lblDNI.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblDNI.setToolTipText("DNI del cliente de la tarea actual.");

        jLabel3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel3.setText("Fecha:");

        lblFecha.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblFecha.setToolTipText("Fecha en la que se realizó la petición.");

        txtDescripcion.setEditable(false);
        txtDescripcion.setColumns(20);
        txtDescripcion.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        txtDescripcion.setLineWrap(true);
        txtDescripcion.setRows(5);
        txtDescripcion.setToolTipText("Descripción del problema del cliente.");
        jScrollPane3.setViewportView(txtDescripcion);

        btnVerPresupuesto.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnVerPresupuesto.setText("Ver Presupuesto");
        btnVerPresupuesto.setToolTipText("Haga click aquí para ver el presupuesto.");
        btnVerPresupuesto.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnVerPresupuestoActionPerformed(evt);
            }
        });

        jButton3.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jButton3.setText("Ver Equipo");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jScrollPane3))
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblDNI, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel3)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblFecha, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(btnVerPresupuesto)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jButton3)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblFecha, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(lblDNI, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(btnVerPresupuesto)
                            .addComponent(jButton3))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(0, 64, Short.MAX_VALUE))
                    .addComponent(jScrollPane3, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                .addContainerGap())
        );

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Servicios prestados", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
        jPanel3.setToolTipText("");

        tablaServiciosPrestados.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        tablaServiciosPrestados.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tablaServiciosPrestados.setToolTipText("Listado de los servicios que se han realizado.");
        tablaServiciosPrestados.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane2.setViewportView(tablaServiciosPrestados);

        comboServicios.setEditable(true);
        comboServicios.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        comboServicios.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        comboServicios.setToolTipText("Cuadro de busqueda y desplegable para buscar servicios dentro del catalogo.");
        comboServicios.addPopupMenuListener(new javax.swing.event.PopupMenuListener() {
            public void popupMenuCanceled(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeInvisible(javax.swing.event.PopupMenuEvent evt) {
            }
            public void popupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {
                comboServiciosPopupMenuWillBecomeVisible(evt);
            }
        });

        btnAñadir.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnAñadir.setText("Añadir");
        btnAñadir.setToolTipText("Haga click aquí para añadir ell servicio a la listado.");
        btnAñadir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAñadirActionPerformed(evt);
            }
        });

        btnQuitar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnQuitar.setText("Quitar");
        btnQuitar.setToolTipText("Haga click aquí para eliminar el servicio seleccionado de la lista.");
        btnQuitar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnQuitarActionPerformed(evt);
            }
        });

        unidades.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        unidades.setModel(new javax.swing.SpinnerNumberModel(Integer.valueOf(1), Integer.valueOf(1), null, Integer.valueOf(1)));
        unidades.setToolTipText("Indique el número de unidades del servicio seleccionado.");

        btnAvisarCambios.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnAvisarCambios.setText("Notificar cambios");
        btnAvisarCambios.setToolTipText("Haga click aquí para notificar al cliente de que no se realizarán los servicios estimados inicialmente.");
        btnAvisarCambios.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAvisarCambiosActionPerformed(evt);
            }
        });
        jPanel5.add(btnAvisarCambios);

        btnFinalizar.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        btnFinalizar.setText("Finalizar");
        btnFinalizar.setToolTipText("Haga click aquí para indicar al cliente que ya ha terminado la tarea.");
        btnFinalizar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnFinalizarActionPerformed(evt);
            }
        });
        jPanel5.add(btnFinalizar);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane2)
                    .addGroup(jPanel3Layout.createSequentialGroup()
                        .addComponent(comboServicios, javax.swing.GroupLayout.PREFERRED_SIZE, 302, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(unidades, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnAñadir)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(btnQuitar)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addComponent(jPanel5, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(comboServicios, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnAñadir)
                    .addComponent(btnQuitar)
                    .addComponent(unidades, javax.swing.GroupLayout.PREFERRED_SIZE, 26, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(6, 6, 6)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 164, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel5, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void comboServiciosPopupMenuWillBecomeVisible(javax.swing.event.PopupMenuEvent evt) {//GEN-FIRST:event_comboServiciosPopupMenuWillBecomeVisible
        if (isFirst && (modeloServicios != null)) {
            isFirst = false;
            modeloServicios.updateModel("");
        }
        
    }//GEN-LAST:event_comboServiciosPopupMenuWillBecomeVisible

    private void btnAñadirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAñadirActionPerformed
        Servicio[] temp = BDServicios.buscar(BDServicios.buscarPorNombre,((String) this.comboServicios.getSelectedItem()), BDServicios.ASC, false);
        boolean modificado = false;
        if (temp[0] != null){
            temp[0].setUnidades(((int)unidades.getValue()));
            for (Servicio s : tareaActual.getServiciosPrestados()){
                if (s.getNombre().equalsIgnoreCase(temp[0].getNombre())){
                    int a = temp[0].getUnidades();
                    int b = s.getUnidades();
                    s.setUnidades(a+b);
                    modificado = true;
                }
            }
           if (!modificado){
               this.tareaActual.addServiciosPrestados(temp[0]);
           }
           this.tablaServiciosPrestados.setModel(new ServiciosPrestadosDefaultTableModel(false, tareaActual.getServiciosPrestados().toArray(new Servicio[0])));
           BDTareas.actualizarPrestados(tareaActual);
        } else{
            Dialogos.mostrarDialogoNoElemento();
        }
    }//GEN-LAST:event_btnAñadirActionPerformed

    private void lstTareasPendientesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_lstTareasPendientesMouseClicked
        // TODO add your handling code here:
        int selectedIndex = this.lstTareasPendientes.getSelectedIndex();
        
        if (selectedIndex != -1){
            String elementAt = (String)this.lstTareasPendientes.getModel().getElementAt(selectedIndex);
            int index = elementAt.indexOf(":");
            index = index +2;
            String id = elementAt.substring(index);
            rellenar(BDTareas.obtener(Long.parseLong(id)));
            this.lstTareasPendientes.setModel(new TareasDefaultListModel());
            this.unidades.setValue(1);
        }
    }//GEN-LAST:event_lstTareasPendientesMouseClicked

    private void btnQuitarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnQuitarActionPerformed
        // TODO add your handling code here:
        int fila = this.tablaServiciosPrestados.getSelectedRow();
        if (fila != -1){
            String valueAt = (String)this.tablaServiciosPrestados.getValueAt(fila, 0);
            int res = Dialogos.mostrarDialogoQuitarServicioPrestado();
            if (res == 0){
                //Borrar todos
                tareaActual.removeServicioPrestado(valueAt);
                this.tablaServiciosPrestados.setModel(new ServiciosPrestadosDefaultTableModel(false, tareaActual.getServiciosPrestados().toArray(new Servicio[0])));
                BDTareas.actualizarPrestados(tareaActual);
            }else {
                if (res == 1){
                    //Borrar algunos
                    this.jDialog1.pack();
                    this.jDialog1.setLocationRelativeTo(null);
                    this.jDialog1.setVisible(true);
                    
                }
            }
        }else {
            Dialogos.mostrarDialogoNoElemento();
        }
    }//GEN-LAST:event_btnQuitarActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
        String valueAt = (String)this.tablaServiciosPrestados.getValueAt(this.tablaServiciosPrestados.getSelectedRow(), 0);
        Servicio buscado = BDServicios.buscar(BDServicios.buscarPorNombre,valueAt , BDServicios.ASC, false)[0];
        for (Servicio temp : tareaActual.getServiciosPrestados().toArray(new Servicio[0])){
            if (temp.getNombre().equalsIgnoreCase(buscado.getNombre())){
                int a = temp.getUnidades();
                int nuevasUnidades  =  a - ((int)jSpinner1.getValue());
                if (nuevasUnidades <= 0){
                    tareaActual.removeServicioPrestado(valueAt);
                }else {
                    temp.setUnidades(nuevasUnidades);
                }
                
            }
        }
        this.tablaServiciosPrestados.setModel(new ServiciosPrestadosDefaultTableModel(false, tareaActual.getServiciosPrestados().toArray(new Servicio[0])));
        BDTareas.actualizarPrestados(tareaActual);
        jDialog1.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed
    private boolean validarPresupuesto(){
        Servicio[] presupuesto = BDPresupuestos.obtenerUltimo(tareaActual.getIdTarea()).getServiciosEstimados();
        boolean correcto = false;
        for (int i = 0; i < this.tablaServiciosPrestados.getRowCount();i++){
            for (Servicio temp : presupuesto){
                String nombre = (String)this.tablaServiciosPrestados.getValueAt(i, 0);
                double sunidades = (int) this.tablaServiciosPrestados.getValueAt(i,1);
                if (temp.getNombre().equalsIgnoreCase(nombre) && sunidades == temp.getUnidades()){
                    correcto = true;
                }
            }
            if (!correcto){break;}
        }
        return correcto;
    }
    private void btnFinalizarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnFinalizarActionPerformed
        if (validarPresupuesto()){
            if ((Dialogos.mostrarDialogoConfirmacion("¿Esta seguro de que desea finalizar la tarea?")) == JOptionPane.YES_OPTION){
                this.tareaActual.setEstado(Estado.FINALIZADO);
                BDTareas.actualizar(tareaActual);
                Aviso a = new Aviso();
                a.setFecha(new GregorianCalendar());
                a.setDescripcion("Tarea finalizada. Ya se puede recoger el equipo.");
                a.setIdTarea(tareaActual.getIdTarea());
                BDAviso.insertar(a);
                this.lblDNI.setText("");
                this.lblFecha.setText("");
                this.txtDescripcion.setText("");
                tareaActual = null;
                this.tablaServiciosPrestados.setModel(new ServiciosPrestadosDefaultTableModel(false));
                this.cambiarEstadoCampos(false);
                this.lstTareasPendientes.setModel(new TareasDefaultListModel());
            }
        } else {
            if ((Dialogos.mostrarDialogoConfirmacion("No se han prestado todos los servicios. ¿Seguro que desea finalizar la tarea?"))==JOptionPane.YES_OPTION){
                this.tareaActual.setEstado(Estado.FINALIZADO);
                BDTareas.actualizar(tareaActual);
                Aviso a = new Aviso();
                a.setFecha(new GregorianCalendar());
                a.setDescripcion("Tarea finalizada. Ya se puede recoger el equipo.");
                a.setIdTarea(tareaActual.getIdTarea());
                BDAviso.insertar(a);
                this.lblDNI.setText("");
                this.lblFecha.setText("");
                this.txtDescripcion.setText("");
                tareaActual = null;
                this.tablaServiciosPrestados.setModel(new ServiciosPrestadosDefaultTableModel(false));
                this.cambiarEstadoCampos(false);
                this.lstTareasPendientes.setModel(new TareasDefaultListModel());
            }
        }
        
    }//GEN-LAST:event_btnFinalizarActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        jDialog1.setVisible(false);
        jDialog1.dispose();
    }//GEN-LAST:event_jButton2ActionPerformed

    private void btnVerPresupuestoActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnVerPresupuestoActionPerformed
        // TODO add your handling code here:
        new VerPresupuesto(this.tareaActual.getIdTarea()).setVisible(true);
    }//GEN-LAST:event_btnVerPresupuestoActionPerformed

    private void btnAvisarCambiosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAvisarCambiosActionPerformed
        AñadirAviso a = new AñadirAviso(this.user,tareaActual);
        a.addWindowListener(new WindowListener(){

            @Override
            public void windowOpened(WindowEvent e) {
                
            }

            @Override
            public void windowClosing(WindowEvent e) {
                
            }

            @Override
            public void windowClosed(WindowEvent e) {
                lstTareasPendientes.setModel(new TareasDefaultListModel());
                cambiarEstadoCampos(false);
            }

            @Override
            public void windowIconified(WindowEvent e) {
                
            }

            @Override
            public void windowDeiconified(WindowEvent e) {
                
            }

            @Override
            public void windowActivated(WindowEvent e) {
                
            }

            @Override
            public void windowDeactivated(WindowEvent e) {
                
            }
        
        });
        a.setVisible(true);
    }//GEN-LAST:event_btnAvisarCambiosActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        Equipo[] equipos = BDAlmacenEquipos.buscar(BDAlmacenEquipos.buscarPorIdTarea, tareaActual.getIdTarea()+"", BDAlmacenEquipos.ASC, true);
        String mensaje ="";
        for (Equipo temp : equipos){
            mensaje = mensaje + "Datos del equipo: \n Número de serie: " + ("".equalsIgnoreCase(temp.getNumeroSerie())?"":temp.getNumeroSerie()) + "\n Marca: " + ("".equalsIgnoreCase(temp.getMarca())?"":temp.getMarca()) + "\n Modelo: " + ("".equalsIgnoreCase(temp.getModelo())?"":temp.getModelo());
        }
        Dialogos.mostrarDialogoInformacion(mensaje);
    }//GEN-LAST:event_jButton3ActionPerformed
    public void rellenar(Tarea tarea){
        cambiarEstadoCampos(true);
        Peticion pet = BDPeticiones.obtener(tarea.getIdTarea());
        this.lblDNI.setText(pet.getCliente().getDni());
        this.lblFecha.setText(ConversorFecha.formateadorFecha(pet.getFecha()));
        this.txtDescripcion.setText(pet.getDescripcion());
        tarea.setServiciosPrestados(BDServicios.obtenerPrestados(tarea.getIdTarea()));
        this.tablaServiciosPrestados.setModel(new ServiciosPrestadosDefaultTableModel(false, tarea.getServiciosPrestados().toArray(new Servicio[0])));
        this.tareaActual = tarea;
        this.tareaActual.setDNICliente(pet.getCliente().getDni());
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VistaTecnico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VistaTecnico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VistaTecnico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VistaTecnico.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form 
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VistaTecnico().setVisible(true);
            }
        });*/
    }
    private class TareasDefaultListModel extends DefaultListModel{
        public TareasDefaultListModel(){
            for (Tarea temp : BDTareas.obtenerTareasTecnico(user.getId())){
                //Si no esta pendiente entonces añadir al listado
                if (temp.getEstado() == Estado.PENDIENTE){
                    this.addElement("Código: " + temp.getIdTarea() );
                }
            }
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAvisarCambios;
    private javax.swing.JButton btnAñadir;
    private javax.swing.JButton btnFinalizar;
    private javax.swing.JButton btnQuitar;
    private javax.swing.JButton btnVerEquipo;
    private javax.swing.JButton btnVerPresupuesto;
    private javax.swing.JComboBox comboServicios;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JDialog jDialog1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JSpinner jSpinner1;
    private javax.swing.JLabel lblDNI;
    private javax.swing.JLabel lblFecha;
    public static javax.swing.JList lstTareasPendientes;
    private javax.swing.JTable tablaServiciosPrestados;
    private javax.swing.JTextArea txtDescripcion;
    private javax.swing.JSpinner unidades;
    // End of variables declaration//GEN-END:variables
}
